<?php

namespace app\zyhsapi\controller\v2;

use app\astrologer\lib\AstrPush;
use app\chat\LiveMessage;
use app\common\cachemodel\OrdersLib;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\lib\Util;
use app\zyhsapi\controller\ZyhsAuth;
use app\zyhsapi\model\ZyhsConsultChatRecord;
use app\zyhsapi\model\ZyhsConsultChatRecordAstr;
use app\zyhsapi\model\ZyhsConsultChatRecordDetails;
use app\zyhsapi\model\ZyhsRecode;
use app\zyhsapi\model\ZyhsUserAccount;
use app\zyhsapi\model\ZyhsUserAccountRecord;
use think\Db;
use think\response\Json;

class ConsultChat extends ZyhsAuth
{
    private $appType1 = 1; // 1=>准有好事 2=>准了APP

    /**
     * 向 会话占星师发送 星盘
     * @return Json
     * @throws \Exception
     */
    public function chatSendRecode()
    {
        $astrId = input('astr_id/d', 0);
        $rid = input('rid/d', 0);
        if (!$astrId || !$rid)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (Util::commentCheck($this->user['id'], ['action' => 'chatSendRecode', 'rid' => $rid, 'astr_id' => $astrId], 5))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $recodeModel = new ZyhsRecode();
        $recode = $recodeModel->getInfoById($rid);
        if (!$recode || $recode['uid'] != $this->user['id'] || $recode['status'] != 1)
        {
            return show(config('code.error'), '服务异常,档案不存在～');
        }
        $consultAccountInfo = (new Zlcr3ConsultAccount())->getInfoById($astrId);
        $isConsult = $consultAccountInfo && $consultAccountInfo['consult_status'] === 1 ? 1 : 0;
        if (!$isConsult)
        {
            return show(config('code.error'), '服务异常，咨询师不存在～');
        }
        $consultChatIdModel = new ZyhsConsultChatRecord();
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $chatId = $consultChatIdModel->getChatIdByAstrId($this->appType1, $this->user['id'], $astrId);
        $nowTime = $this->request->time();
        if (!$chatId)
        {
            $insertData = [
                'app_type' => $this->appType1,
                'uid' => $this->user['id'],
                'astr_id' => $astrId,
                'last_chat_detail_id' => 0,
                'last_chat_detail_time' => 0,
                'create_time' => $nowTime,
            ];
            // 创建新的会话
            $chatId = $consultChatIdModel->SaveData($insertData);
        }
        $zyhsUserAccountModel = new ZyhsUserAccount();
        // 取用户的准币账号余额
        $userCoin = (new ZyhsUserAccount())->getUserCoinFromCache($this->user['id']);
        // 取发送 档案 价格
        $price = config('zyhsgoods.chat_send_recode_price');
        $coinNum = (int)($userCoin['balance'] ?? 0);// 准币余额
        if ($coinNum < $price)
        {
            return show(410, '余额不足，请充值～');
        }
        // 扣除 准币
        $coinNum = $coinNum - $price;
        $consume_price = $userCoin['consume_price'] + OrdersLib::getOrderCoinTotalAmount($price);
        $consume_coin = $userCoin['consume_coin'] + $price;
        //更新用户钱包金额
        $zyhsUserAccountModel->UpdateData($this->user['id'], ['balance' => $coinNum, 'consume_price' => $consume_price, 'consume_coin' => $consume_coin, 'update_time' => $nowTime], ['uid' => $this->user['id']]);
        // 写入 用户 准币流水
        $insertData = [
            'status' => 1,
            'account' => 0,
            'uid' => $this->user['id'],
            'consumer_type' => 2,
            'order_type' => 110,
            'gid' => 0,
            'pray_date' => 0,
            'total_amount' => $price / 10,
            'coin_num' => $price,
            'balance' => $coinNum,
            'order_id' => '',
            'trade_type' => 4,
            'create_time' => $nowTime,
            'extend' => '[]',
        ];
        //增加准币明细记录
        $crid = (new ZyhsUserAccountRecord())->SaveData($this->user['id'], $insertData);
        $utilModel = new Util();
        $sendRecodeInfo = [
            'rid' => $rid,
            'year' => $recode['year'],
            'month' => $recode['month'],
            'day' => $recode['day'],
            'sun' => $utilModel->recodeAstroMiddlehand($recode['sun']),
            'moon' => $utilModel->recodeAstroMiddlehand($recode['moon']),
            'asc' => $utilModel->recodeAstroMiddlehand($recode['asc']),
        ];
        $consultMsgData = [
            'chat_id' => $chatId,
            'app_type' => $this->appType1,
            'uid' => $this->user['id'],
            'astr_id' => $astrId,
            'type' => 2,    //  1=>APP消息 2=>用户发送消息
            'title' => '',
            'content' => '', // 提问问题
            'data_type' => 8,   // 1=>普通消息  2=>图片  3=>语音咨询消息  4=>咨询问题  5=>咨询问题答案 6=>问答悬赏问题回复 7=>问答悬赏追问已回复 8=>用户发送星盘信息
            'extend' => ['intercept_tips' => '', 'recode_info' => $sendRecodeInfo],  //  语音咨询消息 ｜ 图片信息 | 内容拦截信息
            'pid' => 0, // 待更新
            'create_time' => $nowTime,
        ];
        $resData = $consultChatRecordDetailsModel->SaveData($chatId, $consultMsgData);
        if ($resData)
        {   // 更新用户端 最后咨询信息
            $consultChatIdModel->updateData($chatId, [
                'uid' => $this->user['id'],
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTime,
            ], $this->appType1);
            (new ZyhsUserAccountRecord())->UpdateData($this->user['id'], $crid, ['extend' => json_encode(['chat_detail_id' => $resData['id']], JSON_UNESCAPED_UNICODE)], ['id' => $crid]);
            // 更新咨询师端 最后咨询信息
            $zlcr3ConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
            $astrChatInfo = $zlcr3ConsultChatRecordAstrModel->getUserAstrChatInfo($this->appType1, $this->user['id'], $astrId);
            $zlcr3ConsultChatRecordAstrModel->userSendUpdate($this->appType1, $this->user['id'], $astrId, [
                'last_chat_detail_id' => $resData['id'],
                'last_chat_detail_time' => $nowTime,
                'unread_num' => Db::raw('unread_num + 1'),
                'delay_num' => Db::raw('delay_num + 1'),
            ]);

            $resData1 = current($consultChatRecordDetailsModel->userDataListResert([$resData], [], $this->user, $this->appType1));
            // 判断咨询师是否在线
            if (LiveMessage::getUserIsOnline(2, $astrId))
            {   // 向 咨询师发送消息
                $astrData2 = current($consultChatRecordDetailsModel->astrDataListResert([$resData], [], $this->user, $this->appType1));
                LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $astrId), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
                    'msg_type' => 2,
                    'app_type' => $this->appType1,
                    'uid' => $this->user['id'],
                    'num' => $astrChatInfo['delay_num'] + 1,
                    'msg_data' => $astrData2,
                ]);
            }
            $resData1['time_des'] = '';
            $resData1['intercept_tips'] = '';
            $resData1['transaction_id'] = $crid;

            $pushAlert = '[星盘]';
            $pushData = [
                'action' => 'extend',
                'target' => 'local',
                'link' => "chat?id={$this->user['id']}&app_type={$this->appType1}",
                'pop_msg' => json_encode([
                    'avatar' => $this->user['avatar'],
                    'name' => $this->user['nickname'],
                    'msg' => $pushAlert,
                    'target' => 'local',
                    'link' => "chat?id={$this->user['id']}&app_type={$this->appType1}",
                    'uid' => $this->user['id'],
                    'app_type' => $this->appType1,
                ], JSON_UNESCAPED_UNICODE),
            ];
            (new AstrPush())->pushUserMsg($astrId, $pushAlert, $pushData);

            return show(config('code.success'), '请求成功', $resData1);
        }

        return show(config('code.error'), '服务异常，请稍后再试～');
    }
}